package com.ggdog.ggdognetdiskspringboot.controller;


import com.ggdog.ggdognetdiskspringboot.utils.AjaxResult;
import com.ggdog.ggdognetdiskspringboot.utils.MinioUtils;
import io.minio.MinioClient;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;

/**
 * @Description minio文件上传控制器
 */
@CrossOrigin
@RestController
@RequestMapping("/api")
public class MinioFileUploadController {
    @Autowired
    private MinioUtils minioUtils;

    /**
     * @param file     文件
     * @param fileName 文件名称
     * @Description 上传文件
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file,  String fileName,String bucketName) {
        System.out.println(fileName);
        if (minioUtils.isFileExists(fileName,bucketName)) return AjaxResult.error(404,"文件已经存在！");
        return minioUtils.upload(file, fileName,bucketName);
    }

    /**
     * @param fileName 文件名称
     * @Description dowload文件
     */
    @GetMapping("/download")
    public ResponseEntity dowloadFile(@RequestParam("fileName") String fileName,String bucketName) {

        ResponseEntity responseEntity= minioUtils.download(fileName,bucketName);
        HttpStatus status=responseEntity.getStatusCode();
        if(status.toString().equals("200 OK")){
            return responseEntity;
        }
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);

    }

    /**
     * @param fileName 文件名称
     * @Description 得到文件url
     */
    @GetMapping("/getUrl")
    public AjaxResult getFileUrl(@RequestParam("fileName") String fileName,String bucketName) throws Exception {
        if(!minioUtils.isFileExists(fileName,bucketName)) return AjaxResult.error(404,"文件不存在");
        HashMap map=new HashMap();
        map.put("FileUrl",minioUtils.getFileUrl(fileName,bucketName));
        return AjaxResult.success(map);
    }
    /**
     * 删除文件
     *
     * @param fileName 文件路径
     * @return
     */
    @RequestMapping("/deleteFile")
    public AjaxResult deleteFile(String fileName,String bucketName) throws Exception {
        return  minioUtils.deleteFile(fileName,bucketName);

    }
    @RequestMapping("/isFileExists")
    public AjaxResult isFileExists(String fileName,String bucketName){
        if(minioUtils.isFileExists(fileName,bucketName)){
            return AjaxResult.success();
        }else{
            return AjaxResult.error(404,"文件不存在");
        }
    }


}
